//==================================================================================================================
/*:
 * @plugindesc 中途跳過視頻播放 + 標題前播放視頻（老饕修正）。
 * 
 * @author 芯☆淡茹水，老饕修正
 * 
 * @help  
 *
 * 〓 說明 〓
 *
 * 工程在 編輯/測試 時使用的是 webm 格式視頻。
 *
 * 該插件顯示製作好的 跳過視頻 圖片來提示跳過視頻。 圖片保存在 image/system 文件夾裡。
 * 
 * 老饕：
 * 1. 修正了無法進行戰鬥和事件測試的問題。
 * 2. 修正了UI效果及顯示/隱藏的切換邏輯。
 *
 * 〓 插件命令 〓
 *
 * 播放視頻時顯示並能夠操作 跳過視頻 。
 * 在播放視頻前使用插件命令： ShowVideoSkip
 *
 * ※該命令只作用於當前播放視頻（執行命令後第一個播放的視頻）※
 * 
 * @param videoName
 * @desc 標題前播放的視頻文件名（不播放就不寫）。
 * @default 
 *
 * @param titVdSkip
 * @desc 是否可以跳過標題前播放的視頻？ （是：ON；否：OFF）
 * @default ON
 * 
 * @param skipTit
 * @desc 是否跳過標題界面（是：ON; 否：OFF）。
 * @default OFF
 *
 * @param skipX
 * @desc 視頻播放時，跳過提示顯示的 X 座標。
 * @default 640
 * 
 * @param skipY
 * @desc 視頻播放時，跳過提示顯示的 Y 座標。
 * @default 88
 *
 * @param skipKey
 * @desc 跳過視頻播放快捷鍵的鍵盤鍵值(不需要按鍵跳過就不寫)。
 * @default 75
 * 
 * @param skipImage
 * @desc 用圖片製作的 跳過提示 的圖片名（圖片保存在system文件夾）。
 * @default Video_Skip
 *
*/
//==================================================================================================================
;(function(){
var XdRsData = XdRsData  || {};
XdRsData.videoPlay = XdRsData.videoPlay || {};
XdRsData.videoPlay.parameters  =    PluginManager.parameters('XdRs_VideoPlay');
XdRsData.videoPlay.skipX       =   +XdRsData.videoPlay.parameters['skipX']       || 0;
XdRsData.videoPlay.skipY       =   +XdRsData.videoPlay.parameters['skipY']       || 0;
XdRsData.videoPlay.skipImage   = ''+XdRsData.videoPlay.parameters['skipImage']   || '';
XdRsData.videoPlay.name        = ''+XdRsData.videoPlay.parameters['videoName']   || '';
XdRsData.videoPlay.skipTit     = ''+XdRsData.videoPlay.parameters['skipTit'] === 'ON';
XdRsData.videoPlay.titVdSkip   = ''+XdRsData.videoPlay.parameters['titVdSkip'] === 'ON';
//==================================================================================================================
Input.keyMapper[+XdRsData.videoPlay.parameters['skipKey']] = 'skipVideo';
//==================================================================================================================
ConfigManager.videoSkipTip = false;
//==================================================================================================================
XdRsData.videoPlay.GraphicsPlayVideo = Graphics.playVideo;
Graphics.playVideo = function(src) {
    XdRsData.videoPlay.GraphicsPlayVideo.call(this, src);
    this._video.volume = ConfigManager.bgmVolume / 100;
    this._videoLoading = true;
};
Graphics.stopVideo = function() {
    SoundManager.playOk();
    this._video.currentTime = 0;
    this._video.pause();
    this._updateVisibility(false);
};
Graphics.videoIsLoading = function() {
    return this._videoLoading && !this.isVideoPlaying();
};
XdRsData.videoPlay.Graphics_createAllElements = Graphics._createAllElements;
Graphics._createAllElements = function() {
    XdRsData.videoPlay.Graphics_createAllElements.call(this);
    this._createSkipCanvas();
};
Graphics._createSkipCanvas = function() {
    this._skipCanvas = document.createElement('canvas');
    this._context = this._skipCanvas.getContext('2d');
    document.body.appendChild(this._skipCanvas);
    var rw = this._width - window.innerWidth;
    var rh = this._height - window.innerHeight - 1;
    window.resizeBy(rw, rh); window.resizeBy(rw, rh+1);
};
XdRsData.videoPlay.Graphics_onVideoLoad = Graphics._onVideoLoad;
Graphics._onVideoLoad = function() {
    XdRsData.videoPlay.Graphics_onVideoLoad.call(this);
    //ConfigManager.videoSkipTip && this._showSkip();    //SWDA：視頻開始時不顯示
};
XdRsData.videoPlay.Graphics_updateVisibility = Graphics._updateVisibility;
Graphics._updateVisibility = function(videoVisible) {
    XdRsData.videoPlay.Graphics_updateVisibility.call(this, videoVisible);
    this._skipCanvas.style.opacity = this._video.style.opacity;
    !videoVisible && this._clearContext();
    this._videoLoading = false;
};
Graphics._clearContext = function() {
    ConfigManager.videoSkipTip = false;
    this._hideSkip();
};
Graphics._showSkip = function() {
    if (!XdRsData.videoPlay.skipImage) return;

    var bitmap = ImageManager.loadSystem(XdRsData.videoPlay.skipImage);
    bitmap.addLoadListener(function() {
        var text = "按任意鍵跳過"
        var [tx, ty, tw] = [1280-22 - 22*6,720 - 22, 22*6];
        this._context.globalCompositeOperation = 'source-over';
        this._skipW = bitmap.width; this._skipH = bitmap.height;
        //var x = XdRsData.videoPlay.skipX, y = XdRsData.videoPlay.skipY;    //SWDA：原版座標已不需要
        this._context.drawImage(bitmap._canvas, 0, 0, 26, 26, tx - 32, ty - 20, 26, 26);
        this._context.fillStyle = '#ffffff';
        this._context.strokeStyle = '#000000';
        this._context.font = '22px sans-serif';
        this._context.lineWidth = 4;
        this._context.lineJoin = 'round';
        this._context.strokeText(text, tx, ty, tw);
        this._context.fillText(text, tx, ty, tw);
        this._context.restore();
        this.isVideoSkipShowing = true;
    }.bind(this));
};

Graphics._hideSkip = function() {
    if(!this.isVideoSkipShowing) return;

    this.isVideoSkipShowing = false;
    this._skipW = this._skipH = null;
    this._context.clearRect(0, 0, this._width, this._height);
};
XdRsData.videoPlay.Graphics_updateAllElements = Graphics._updateAllElements;
Graphics._updateAllElements = function() {
    XdRsData.videoPlay.Graphics_updateAllElements.call(this);
    this._updateSkipCanvas();
};
Graphics._updateSkipCanvas = function() {
    this._skipCanvas.width = this._width;
    this._skipCanvas.height = this._height;
    this._skipCanvas.style.zIndex = 2;
    this._centerElement(this._skipCanvas);
};
/*
//SWDA：已無需判斷觸摸區域
Graphics._touchInSkip = function() {
    var x = XdRsData.videoPlay.skipX, y = XdRsData.videoPlay.skipY;
    return TouchInput.x > x && TouchInput.x < x + this._skipW &&
           TouchInput.y > y && TouchInput.y < y + this._skipH;
};
*/
Graphics.setVideoSkipCount = function() {
    this.videoSkipCount = Graphics.videoSkipCountFrame();   // SWDA：自動關閉時間
};

Graphics.videoSkipCountFrame = function() {
    return 60
    //return CP.CustomMouseCursor.MOUSE_WAIT_COUNT;   // SWDA：與滑鼠時間一致
};

// SWDA：跳過的條件：改為按任意鍵跳過
Graphics.isSkiped = function() {
    const isAnyKeyPressed = Input._latestButton && Input._pressedTime === 0;
    const countCondition = this.videoSkipCount < Graphics.videoSkipCountFrame();
    const keyCondition = isAnyKeyPressed;
    const touchCondition = TouchInput.isTriggered();
    return (keyCondition || touchCondition) && countCondition && this.isVideoSkipShowing;
};

// SWDA：顯示跳過視頻UI的條件：
Graphics.canShowVideoSkip = function() {
    const isAnyKeyPressed = Input._latestButton && Input._pressedTime === 0;
    return (isAnyKeyPressed || TouchInput.isTriggered()) && this.isVideoPlaying() && ConfigManager.videoSkipTip && !this.isVideoSkipShowing;
};

// SWDA：隱藏跳過視頻UI的條件
Graphics.canHideVideoSkip = function() {
    const isAnyKeyPressed = Input._latestButton && Input._pressedTime === 0;
    return (this.videoSkipCount == 0) && !(isAnyKeyPressed || TouchInput.isTriggered()) && this.isVideoSkipShowing;
};

// SWDA：覆寫，需放在CP_CustomMouseCursor之下
TouchInput.changeMousePosition = function(event){
	var x = Graphics.pageToCanvasX(event.pageX);
    var y = Graphics.pageToCanvasY(event.pageY);

    CP.CustomMouseCursor.setMousePosition(x, y);
    CP.CustomMouseCursor.resetMouseWaitCount();
    SceneManager.showMouse();

    // SWDA：新增滑鼠移動觸發跳過視頻界面顯示
	if(Graphics.isVideoPlaying() && ConfigManager.videoSkipTip){
        Graphics.setVideoSkipCount();
        // SWDA：滑鼠按下時不能響應變化！否則不論界面是否顯示，均會立即執行跳過動畫
        if(!Graphics.isVideoSkipShowing && !TouchInput.isPressed() && !TouchInput.isTriggered()){
            Graphics._showSkip();
        }
    }
};


//==================================================================================================================
XdRsData.videoPlay.SMupdateMain = SceneManager.updateMain;
SceneManager.updateMain = function() {
    XdRsData.videoPlay.SMupdateMain.call(this);
    this.updateVideoSkip();
    Graphics.isVideoPlaying() && Graphics.isSkiped() && Graphics.stopVideo();
};

// SWDA：更新跳過動畫相關的內容：
SceneManager.updateVideoSkip = function() {
    if (Graphics.videoSkipCount > 0)
        Graphics.videoSkipCount -= 1;
    if(Graphics.canShowVideoSkip()){
        Graphics.setVideoSkipCount();
        Graphics._showSkip();
    }
    if(Graphics.canHideVideoSkip()){
        Graphics._hideSkip();
    };
};
//==================================================================================================================
XdRsData.videoPlay.GIpluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
    XdRsData.videoPlay.GIpluginCommand.call(this, command, args);
    if (command === 'ShowVideoSkip') ConfigManager.videoSkipTip = true;
};
//==================================================================================================================
Scene_Boot.prototype.start = function() {
    Scene_Base.prototype.start.call(this);
    SoundManager.preloadImportantSounds();
    if (DataManager.isBattleTest()) {
        DataManager.setupBattleTest();
        SceneManager.goto(Scene_Battle);
    } else if (DataManager.isEventTest()) {
        DataManager.setupEventTest();
        SceneManager.goto(Scene_Map);
    } else {
        XdRsData.videoPlay.name && this.playVideo();
    }
    this.updateDocumentTitle();
};
Scene_Boot.prototype.startNewGame = function() {
    this.checkPlayerLocation();
    DataManager.setupNewGame();
    SceneManager.goto(XdRsData.videoPlay.skipTit ? Scene_Map : Scene_Title);
    Window_TitleCommand.initCommandPosition();
};
Scene_Boot.prototype.getVideoType = function() {
    return Graphics.canPlayVideoType('video/webm') && !Utils.isMobileDevice() ? '.webm' : '.mp4';
};
Scene_Boot.prototype.playVideo = function() {
    ConfigManager.videoSkipTip = XdRsData.videoPlay.titVdSkip;
    Graphics.playVideo('movies/' + XdRsData.videoPlay.name + this.getVideoType());
};
XdRsData.videoPlay.SBupdate = Scene_Boot.prototype.update;
Scene_Boot.prototype.update = function() {
    XdRsData.videoPlay.SBupdate.call(this);
    if (Graphics.videoIsLoading()) return;
    //老饕：增加判定條件，否則無法進行戰鬥或事件測試
    if (!DataManager.isBattleTest()&&!DataManager.isEventTest()) {
        !Graphics.isVideoPlaying() && this.startNewGame(); 
    }
};
}());
//==================================================================================================================
//==================================================================================================================